import React from "react"
import { View, Swiper, SwiperItem, Image, ScrollView, Navigator } from "@tarojs/components"
import Taro from "@tarojs/taro"
import GpContainer from "@/components/GpContainer"
import GpBlockTitle from "@/components/GpBlockTitle"
import GpScrollLoading from "@/components/GpScrollLoading"
import GpMustReadItem from "@/components/GpMustReadItem"
import GpJumpNavs from "@/components/GpJumpNavs"
import GpCurrentPort from "@/components/GpCurrentPort"
import GpTabbar from "@/components/GpTabbar"
import { getModuleDetail, getExamList } from "@/apis/index"
import clsx from "clsx"
import { pageMapper } from "@/constants/pageMap"
import { setPageMeta } from "@/utils/common"
import styles from "./index.module.scss"

type IState = {
  detailInfo: Partial<IApiRelative.IGetModuleDetail.IResData>
  newsCurrent: number
  hasNext: boolean
  list: any[]
  navigationTitle: string
}
type IExtData = {
  query: Recordable
  pageMeta: Partial<IApiRelative.IGetModuleDetail.IResData["seo"]>
}
export default class ModuleDetail extends React.Component<unknown, IState> {
  extData: IExtData
  constructor(props) {
    super(props)
    this.state = {
      detailInfo: {
        hotRecoms: []
      },
      newsCurrent: 1,
      hasNext: true,
      list: [],
      navigationTitle: ""
    }
    this.extData = {
      query: {},
      pageMeta: {}
    }
  }
  onReachBottom() {
    const { hasNext, newsCurrent } = this.state
    if (hasNext) {
      this.fetchModuleNews(newsCurrent + 1)
    }
  }
  /** 轮播 */
  renderSwiper = () => {
    const { detailInfo } = this.state
    return (
      <View>
        <Swiper
          className="h-248px"
          indicatorColor="rgba(255, 255, 255, 0.5)"
          indicatorActiveColor="#FFFFFF"
          circular
          indicatorDots
          autoplay
        >
          <SwiperItem>
            <View
              hoverClass="none"
              className="w-690px h-248px rounded-16px bg-hex-ff0 overflow-hidden mx-auto"
            >
              <Image
                src={detailInfo.picture as string}
                className="w-690px h-248px"
                mode="aspectFill"
              />
            </View>
          </SwiperItem>
        </Swiper>
      </View>
    )
  }
  /** 热门推荐 */
  renderRecommend() {
    const { detailInfo } = this.state
    if (!detailInfo.hotRecoms || detailInfo.hotRecoms.length === 0) return null
    const len = detailInfo.hotRecoms.length
    const bgColors = ["#d9ecff", "#E5E9FC", "#DBFCFE"]
    return (
      <View className="pt-60px">
        <View className="pb-30px px-30px">
          <GpBlockTitle title="热门推荐" />
        </View>
        <ScrollView scrollX className="w-750px box-border whitespace-nowrap">
          {detailInfo.hotRecoms.map((l, i) => (
            <View
              key={l.columnId}
              className={clsx("inline-block box-border rounded-12px ", styles["recommend-item"], {
                [styles["first-child"]]: i === 0,
                [styles["last-child"]]: i === len - 1
              })}
              style={{
                backgroundColor: bgColors[i % bgColors.length]
              }}
            >
              <Navigator
                url={"/" + pageMapper.columnDetail + "?id=" + l.columnId}
                className="flex flex-col justify-center items-center box-border text-32px text-hex-334B64 h-full"
              >
                {l.columnName}
              </Navigator>
            </View>
          ))}
        </ScrollView>
      </View>
    )
  }
  /** 渲染列表 */
  renderNewsList = () => {
    const { list } = this.state
    const len = list.length
    if (len <= 0) return null
    return (
      <View className="pt-60px">
        <View className="pb-30px px-30px">
          <GpBlockTitle title="最新动态" />
        </View>
        <View className="px-30px flex flex-col pb-26px">
          {list.map((l, index) => (
            <GpMustReadItem
              key={l.id}
              mustReadItem={l}
              className={clsx({
                "mb-48px": index !== len - 1
              })}
            />
          ))}
        </View>
      </View>
    )
  }
  onShareAppMessage() {}
  onLoad(query: Recordable) {
    this.extData.query = query
    this.fetchModuleDetail()
    this.fetchModuleNews(1)
  }
  componentDidShow() {
    this.setPageInfo()
  }
  setPageInfo() {
    const seo = this.extData.pageMeta
    if (seo.title) {
      setPageMeta({
        keywords: seo.keywords as string,
        description: seo.description as string,
        title: seo.title
      })
    }
  }
  fetchModuleDetail() {
    const { query } = this.extData
    Taro.showLoading()
    return getModuleDetail({
      modulesId: Number(query.id)
    })
      .then(res => {
        if (res.data) {
          this.setState({
            detailInfo: res.data.data,
            navigationTitle: res.data.data.name
          })
          Taro.setNavigationBarTitle({
            title: res.data.data.name
          })
          this.extData.pageMeta = res.data.data.seo
          this.setPageInfo()
        }
      })
      .finally(() => {
        Taro.hideLoading()
      })
  }
  fetchModuleNews(page = 1) {
    const { list } = this.state
    const { query } = this.extData
    return getExamList({
      search: {
        moduleId: Number(query.id)
      },
      pagination: {
        current: page,
        pageSize: 10
      }
    }).then(res => {
      if (res.data) {
        this.setState({
          list: page === 1 ? res.data.data.list : list.concat(res.data.data.list),
          newsCurrent: page,
          hasNext: res.data.data.pagination.current + 1 <= res.data.data.pagination.pageCount
        })
      }
    })
  }
  /** 快捷导航 */
  renderJumpNavs = () => {
    return (
      <View className="mt-20px">
        <GpJumpNavs />
      </View>
    )
  }
  render() {
    const { hasNext, navigationTitle } = this.state
    return (
      <GpContainer className="index">
        <View className="bg-hex-fff pt-20px">
          {/* 轮播 */}
          {this.renderSwiper()}
          {/* 热门推荐 */}
          {this.renderRecommend()}
          {this.renderNewsList()}
        </View>
        {hasNext ? (
          <GpScrollLoading />
        ) : (
          <React.Fragment>
            {/* 快捷导航 */}
            {this.renderJumpNavs()}
            {/* 当前位置 */}
            <GpCurrentPort />
          </React.Fragment>
        )}
        {/* 底部导航 */}
        <GpTabbar type={16} navigationTitle={navigationTitle} />
      </GpContainer>
    )
  }
}
